package com.vict.util;

import lombok.Data;

import java.util.concurrent.*;

@Data
public class TaskUtil {

    private int sameTimeWorkThread = 1;
    private ExecutorService executorService;
    private Semaphore semaphore;

    private TaskUtil(){}

    public TaskUtil(int sameTimeWorkThread){
        this.sameTimeWorkThread = sameTimeWorkThread;
        this.executorService = Executors.newFixedThreadPool(sameTimeWorkThread);
        this.semaphore = new Semaphore(this.sameTimeWorkThread);
    }

    public interface Task<T>{
        T run();
    }

    public <T> Future<T> run(Task<T> task) {
        try{
            this.semaphore.acquire();
            Future<T> future = executorService.submit(() -> {
                try{
                    T t = task.run();
                    return t;
                }finally{
                    this.semaphore.release();
                }
            });

            return future;
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        TaskUtil taskUtil = new TaskUtil(5);
        while(true){
            taskUtil.run(() -> {
                try {
                    Thread.sleep(1000l);
                    System.out.println(123);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return 123;
            });
        }
    }
}
